<template>
  <div class="page">
    <div class="container">
      <el-tabs
        :stretch="true"
        type="border-card"
        v-model="activeName"
        class="tabs"
        @tab-click="handleClick"
      >
        <el-tab-pane
          v-for="(tab, index) in tabs"
          :key="tab.name"
          :label="tab.label"
          :name="tab.name"
        >
          <div class="form-wrapper">
            <el-form
              :ref="(el:any)=>{formRefs[index]=el}"
              :model="tab.formData"
              :rules="tab.rules"
              label-width="100px"
              class="form-inner"
              :validate-on-rule-change="false"
            >
              <!--UserLogin-->
              <template v-if="tab.name === 'first'">
                <el-form-item label="用户名" prop="username">
                  <el-input
                    v-model="tab.formData.username"
                    placeholder="用户名"
                    :prefix-icon="User"
                    size="large"
                  />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input
                    show-password
                    placeholder="密码"
                    type="password"
                    v-model="tab.formData.password"
                    :prefix-icon="Unlock"
                    size="large"
                  />
                </el-form-item>
                <el-form-item class="form-btn-group">
                  <el-button
                    type="primary"
                    size="large"
                    @click="handleUserLogin"
                    class="submit-btn"
                    >立即登录</el-button
                  >
                </el-form-item>
              </template>
              <!--UserRegister-->
              <template v-if="tab.name === 'second'">
                <el-form-item label="用户名" prop="username">
                  <el-input
                    v-model="tab.formData.username"
                    placeholder="用户名"
                    :prefix-icon="User"
                    size="large"
                  />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input
                    show-password
                    placeholder="密码"
                    type="password"
                    v-model="tab.formData.password"
                    :prefix-icon="Unlock"
                    size="large"
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    show-password
                    placeholder="确认密码"
                    type="password"
                    v-model="tab.formData.confirmPassword"
                    :prefix-icon="Unlock"
                    size="large"
                  />
                </el-form-item>
                <el-form-item label="选择角色" prop="role">
                  <el-select
                    v-model="tab.formData.role"
                    placeholder="选择角色"
                    class="full-width"
                    size="large"
                  >
                    <el-option label="医生" value="DOCTOR"></el-option>
                    <el-option label="医疗保健" value="HEALTHCARE"></el-option>
                    <el-option label="机构" value="INSTITUTION"></el-option>
                    <el-option label="研究员" value="RESEARCHER"></el-option>
                    <el-option label="管理员" value="ADMIN"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="电子邮箱" prop="email">
                  <el-input
                    v-model="tab.formData.email"
                    type="email"
                    placeholder="电子邮箱"
                    :prefix-icon="Message"
                    size="large"
                  />
                </el-form-item>
                <el-form-item class="form-btn-group">
                  <el-button
                    type="primary"
                    size="large"
                    @click="handleUserRegister"
                    class="submit-btn"
                    >立即注册</el-button
                  >
                </el-form-item>
              </template>
              <!--GuestLogin-->
              <template v-if="tab.name === 'third'">
                <el-form-item label="游客名称" prop="guestName">
                  <el-input
                    v-model="tab.formData.guestName"
                    placeholder="游客名称"
                    :prefix-icon="Postcard"
                    size="large"
                  />
                </el-form-item>
                <el-form-item class="form-btn-group">
                  <el-button
                    type="warning"
                    size="large"
                    @click="handleGuestLogin"
                    class="submit-btn"
                    >游客访问</el-button
                  >
                </el-form-item>
              </template>
              <!--PatientLogin-->
              <template v-if="tab.name === 'forth'">
                <el-form-item label="患者名" prop="username">
                  <el-input
                    v-model="tab.formData.username"
                    placeholder="用户名"
                    :prefix-icon="User"
                    size="large"
                  />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input
                    show-password
                    placeholder="密码"
                    type="password"
                    v-model="tab.formData.password"
                    :prefix-icon="Unlock"
                    size="large"
                  />
                </el-form-item>
                <el-form-item class="form-btn-group">
                  <el-button
                    type="success"
                    size="large"
                    @click="handlePatientLogin"
                    class="submit-btn"
                    >立即登录</el-button
                  >
                </el-form-item>
              </template>
              <!--PatientRegister-->
              <template v-if="tab.name === 'fifth'">
                <el-form-item label="患者名" prop="username">
                  <el-input
                    v-model="tab.formData.username"
                    placeholder="患者名"
                    :prefix-icon="User"
                    size="large"
                  />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input
                    show-password
                    placeholder="密码"
                    type="password"
                    v-model="tab.formData.password"
                    :prefix-icon="Unlock"
                    size="large"
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    show-password
                    placeholder="确认密码"
                    type="password"
                    v-model="tab.formData.confirmPassword"
                    :prefix-icon="Unlock"
                    size="large"
                  />
                </el-form-item>
                <el-form-item class="form-btn-group">
                  <el-button
                    type="success"
                    size="large"
                    @click="handlePatientRegister"
                    class="submit-btn"
                    >立即注册</el-button
                  >
                </el-form-item>
              </template>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import verify from "../../utils/verify";
import { ref, getCurrentInstance, nextTick } from "vue";
const instance = getCurrentInstance();
const proxy = instance?.proxy as any;
import { useRouter, Router } from "vue-router";
// const route: RouteLocationNormalized = useRoute();
const router: Router = useRouter();
import { useUserStore } from "@/stores/userStore";
const userStore = useUserStore();
import { usePatientDiagnosisStore } from "@/stores/patientDiagnosisStore";
const patientDiagnosisStore = usePatientDiagnosisStore();

import { User, Message, Unlock, Postcard } from "@element-plus/icons-vue";

//五个表单接口
import {
  UserLoginForm,
  UserRegisterForm,
  GuestLoginForm,
  PatientLoginForm,
  PatientRegisterForm,
} from "@/types/form";

//请求参数接口
import { RequestParams } from "@/types/request";

//用户信息接口
import { UserInfo } from "@/types/user";
import { ElForm } from "element-plus";

//独立表单变量
const userLoginForm = ref<UserLoginForm>({ username: "", password: "" });
const userRegisterForm = ref<UserRegisterForm>({
  username: "",
  password: "",
  confirmPassword: "",
  role: "HEALTHCARE",
  email: "",
});
const guestLoginForm = ref<GuestLoginForm>({
  guestName: "",
});
const patientLoginForm = ref<PatientLoginForm>({ username: "", password: "" });
const patientRegisterForm = ref<PatientRegisterForm>({
  username: "",
  password: "",
  confirmPassword: "",
});

//标签页接口,formdata类型与name关联
//keyof...是生成一个对应类型的键名的联合类型，Name只能是其中一个，=后面是设置默认值
// interface TabItem<Name extends keyof TabNameToForm = keyof TabNameToForm> {
//   label: string;
//   name: Name;
//   formData: Ref<TabNameToForm[Name]>;
//   rules?: FormRules;
//   formRef?: Ref<any>;
// }
const activeName = ref<string>("first");
const formRefs = ref<Array<InstanceType<typeof ElForm> | null>>([]);
const tabs = ref([
  {
    label: "用户登录",
    name: "first" as const,
    formData: userLoginForm,
    rules: {
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        {
          validator: verify.username,
          message:
            "用户名格式不正确，必须是4-16个字符，只能包含数字、字母和下划线",
          trigger: "blur",
        },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        {
          validator: verify.password,
          message:
            "密码格式不正确，必须至少8个字符，包含一个数字、一个大写字母、一个小写字母和一个特殊字符",
          trigger: "blur",
        },
      ],
    },
  },
  {
    label: "用户注册",
    name: "second" as const,
    formData: userRegisterForm,
    rules: {
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        {
          validator: verify.username,
          message:
            "用户名格式不正确，必须是4-16个字符，只能包含数字、字母和下划线",
          trigger: "blur",
        },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        {
          validator: verify.password,
          message:
            "密码格式不正确，必须至少8个字符，包含一个数字、一个大写字母、一个小写字母和一个特殊字符",
          trigger: "blur",
        },
      ],
      confirmPassword: [
        { required: true, message: "请输入确认密码", trigger: "blur" },
        {
          validator: (
            _: any,
            value: string,
            callback: (error?: Error) => void
          ) => {
            checkConfirmPassword(
              value,
              callback,
              userRegisterForm.value.password
            );
          },
          trigger: "blur",
        },
      ],
      email: [
        { required: true, message: "请输入电子邮箱", trigger: "blur" },
        {
          validator: verify.email,
          message: "请输入有效的邮箱地址",
          trigger: "blur",
        },
      ],
      role: [{ required: true, message: "请选择角色", trigger: "change" }],
    },
  },
  {
    label: "游客登录",
    name: "third" as const,
    formData: guestLoginForm,
    rules: {
      guestName: [
        { required: true, message: "请输入游客名称", trigger: "blur" },
        { min: 2, max: 10, message: "名称控制在2-10个字符", trigger: "blur" },
      ],
    },
  },
  {
    label: "患者登录",
    name: "forth" as const,
    formData: patientLoginForm,
    rules: {
      username: [
        { required: true, message: "请输入患者名", trigger: "blur" },
        {
          validator: verify.username,
          message:
            "患者名格式不正确，必须是4-16个字符，只能包含数字、字母和下划线",
          trigger: "blur",
        },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        {
          validator: verify.password,
          message:
            "密码格式不正确，必须至少8个字符，包含一个数字、一个大写字母、一个小写字母和一个特殊字符",
          trigger: "blur",
        },
      ],
    },
  },
  {
    label: "患者注册",
    name: "fifth" as const,
    formData: patientRegisterForm,
    rules: {
      username: [
        { required: true, message: "请输入患者名", trigger: "blur" },
        {
          validator: verify.username,
          message:
            "患者名格式不正确，必须是4-16个字符，只能包含数字、字母和下划线",
          trigger: "blur",
        },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        {
          validator: verify.password,
          message:
            "密码格式不正确，必须至少8个字符，包含一个数字、一个大写字母、一个小写字母和一个特殊字符",
          trigger: "blur",
        },
      ],
      confirmPassword: [
        { required: true, message: "请输入确认密码", trigger: "blur" },
        {
          validator: (
            _: any,
            value: string,
            callback: (error?: Error) => void
          ) => {
            checkConfirmPassword(
              value,
              callback,
              patientRegisterForm.value.password
            );
          },
          trigger: "blur",
        },
      ],
    },
  },
]);

//密码一致性
const checkConfirmPassword = (
  value: string,
  callback: (error?: Error) => void,
  password: string
) => {
  if (value) {
    if (value === password) {
      callback();
    } else {
      callback(new Error("两次输入密码不一致"));
    }
  } else {
    callback(new Error("请输入确认密码"));
  }
};

const handleUserLogin = async () => {
  const currentTabIndex = tabs.value.findIndex((tab) => tab.name === "first");
  if (currentTabIndex === -1) {
    proxy.message.error("未找到用户登录表单");
    return;
  }
  await nextTick();
  const formInstance = formRefs.value[currentTabIndex];
  if (!formInstance) {
    proxy.message.warning("表单未加载完成，请稍后再试");
    return;
  }
  try {
    await formInstance.validate();
    const data: RequestParams = {
      username: userLoginForm.value.username,
      password: userLoginForm.value.password,
    };
    const result: any = await userStore.login(data);
    if (!result) {
      return;
    }
    if (result.code === 1) {
      let userData: UserInfo = {} as UserInfo;
      userData = result.data;
      if (userData.role === "ADMIN") {
        router.push("/admin");
      } else {
        router.push("/user");
      }
    }
  } catch (error) {
    console.log(error);
  }
};
const handleUserRegister = async () => {
  const currentTabIndex = tabs.value.findIndex((tab) => tab.name === "second");
  if (currentTabIndex === -1) {
    proxy.message.error("未找到用户注册表单");
    return;
  }
  await nextTick();
  const formInstance = formRefs.value[currentTabIndex];
  if (!formInstance) {
    proxy.message.warning("表单加载未完成，请稍后再试");
    return;
  }
  try {
    await formInstance.validate();
    const data: RequestParams = {
      username: userRegisterForm.value.username,
      password: userRegisterForm.value.password,
      email: userRegisterForm.value.email,
      role: userRegisterForm.value.role,
    };
    let result: any = await userStore.register(data);
    if (!result) return;
    //填充登录信息
    if (result.code === 1) {
      userLoginForm.value.username = userStore.getUserData().username;
      userLoginForm.value.password = userRegisterForm.value.password;
      activeName.value = "first";
    }
  } catch (error) {
    console.log(error);
  }
};
const handleGuestLogin = async () => {
  //游客不需要请求
  const currentTabIndex = tabs.value.findIndex((tab) => tab.name === "third");
  if (currentTabIndex === -1) {
    proxy.message.error("未找到游客表单");
    return;
  }
  await nextTick();
  const formInstance = formRefs.value[currentTabIndex];
  if (!formInstance) {
    proxy.message.warning("表单加载未完成，请稍后再试");
    return;
  }
  try {
    await formInstance.validate();
    const formValue: string = formInstance.fields.find(
      (f: any) => f.prop === "guestName"
    )?.fieldValue;
    if (formValue) {
      proxy.message.success("游客登陆成功");
      sessionStorage.setItem("guestName", formValue);
      router.push("/visitor");
    } else {
      proxy.message.error("游客登录失败，请检查信息");
    }
  } catch (error) {
    console.log(error);
  }
};
const handlePatientLogin = async () => {
  const currentTabIndex = tabs.value.findIndex((tab) => tab.name === "forth");
  if (currentTabIndex === -1) {
    proxy.message.error("未找到患者登录表单");
    return;
  }
  await nextTick();
  const formInstance = formRefs.value[currentTabIndex];
  if (!formInstance) {
    proxy.message.warning("表单加载未完成，请稍后再试");
    return;
  }
  try {
    await formInstance.validate();
    const data: RequestParams = {
      username: patientLoginForm.value.username,
      password: patientLoginForm.value.password,
    };
    let result: any = await patientDiagnosisStore.login(data);
    if (!result) return;
    if (result.code === 1) {
      router.push("/patient");
    }
  } catch (error) {
    console.log(error);
  }
};
const handlePatientRegister = async () => {
  const currentTabIndex = tabs.value.findIndex((tab) => tab.name === "fifth");
  if (currentTabIndex === -1) {
    proxy.message.error("未找到患者注册表单");
    return;
  }
  await nextTick();
  const formInstance = formRefs.value[currentTabIndex];
  if (!formInstance) {
    proxy.message.warning("表单加载未完成，请稍后再试");
    return;
  }
  try {
    await formInstance.validate();
    const data: RequestParams = {
      username: patientRegisterForm.value.username,
      password: patientRegisterForm.value.password,
    };
    let result: any = await patientDiagnosisStore.register(data);
    if (!result) return;
    //填充患者登录信息
    if (result.code === 1) {
      patientLoginForm.value.username =
        patientDiagnosisStore.getPatientInfo().username;
      patientLoginForm.value.password = patientRegisterForm.value.password;
      activeName.value = "forth";
    }
  } catch (error) {
    console.log(error);
  }
};
const handleClick = () => {};
</script>

<style scoped>
.page {
  min-height: 98vh;
  display: flex;
  background-size: cover;
  background-position: top;
  /* align-items: center; */
  justify-content: center;
  background-repeat: no-repeat;
  background-attachment: scroll;
  background-image: url("@/assets/Login-bg.png");
}
.container {
  margin-top: 18rem;
  width: 30%;
  max-width: 800px;
  min-width: 300px;
  padding: 20px;
  /* background-color: rgba(255,255,255,0.7); */
  /* backdrop-filter: blur(5px); */
}
.tabs {
  padding: 32px 32px 0px 32px;
  color: #606772;
  font-size: 32px;
  font-weight: 600;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
}
.submit-btn {
  width: 75%;
  margin-top: 1.5rem;
  padding: 12px;
  font-size: 1rem;
  transition: all 0.3s ease;
}
.form-wrapper {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}
.form-inner {
  width: 80%;
  max-width: 400px;
  margin-right: 50px;
}
.form-btn-group {
  display: flex;
  justify-content: center;
}
</style>
